package com.example.fragmentbrowser

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import androidx.core.view.size
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator

class MainActivity : AppCompatActivity() {

    private lateinit var viewPager: ViewPager2
    private lateinit var tabsPagerAdapter: TabsPagerAdapter
    private lateinit var tabLayout: TabLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewPager = findViewById(R.id.viewPager)
        tabLayout = findViewById(R.id.tabLayout)
        val addButton: Button = findViewById(R.id.addFragmentButton)

        tabsPagerAdapter = TabsPagerAdapter(this)
        viewPager.adapter = tabsPagerAdapter

        TabLayoutMediator(tabLayout, viewPager) { tab, position ->
            tab.text = "Tab ${position + 1}"
        }.attach()

        addButton.setOnClickListener {
            val nextFragmentNumber = tabsPagerAdapter.itemCount + 1
            addNewTab(MyFragment.newInstance(nextFragmentNumber))
        }
    }

    private fun addNewTab(fragment: Fragment) {
        tabsPagerAdapter.addFragment(fragment)
        viewPager.currentItem = tabsPagerAdapter.itemCount - 1 // 切换到新添加的Fragment
    }
}